package com.imooc.utils.ffmpeg;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;

public class FFMpegConvertUtils {


    /**
     * 音视频合并
     *
     * @param ffmpegExePath
     * @param videoFilePath
     * @param duration
     * @param outputVideoPath
     */
    public void convertor(String ffmpegExePath, String videoFilePath, String audioFilePath, double duration, String outputVideoPath) {
        List<String> command = new ArrayList<String>();
        command.add(ffmpegExePath);
        command.add("-i");
        command.add(videoFilePath);
        command.add("-i");
        command.add(audioFilePath);


        command.add("-c:v");
        command.add("copy");
        command.add("-c:a");
        command.add("aac");
        command.add("-strict");
        command.add("experimental");
        command.add("-map");
        command.add("0:v:0");
        command.add("-map");
        command.add("1:a:0");
        command.add(outputVideoPath);
        ProcessBuilder builder = new ProcessBuilder();
        builder.command(command);
    /*    ffmpeg -i video.mp4 -i audio.wav -c:v copy -c:a aac -strict experimental
                -map 0:v:0 -map 1:a:0 output.mp4*/
        //正常信息和错误信息合并输出
        builder.redirectErrorStream(true);
        try {
            //开始执行命令
            Process process = builder.start();
            //如果你想获取到执行完后的信息，那么下面的代码也是需要的
            StringBuffer sbf = new StringBuffer();
            String line = null;
            InputStream inputStream = process.getErrorStream();
            InputStreamReader inputStreamReader = new InputStreamReader(inputStream);
            BufferedReader br = new BufferedReader(inputStreamReader);
            while ((line = br.readLine()) != null) {
                sbf.append(line);
                sbf.append(" ");
            }
            String resultInfo = sbf.toString();
            System.out.println(resultInfo);
            if (br != null) {
                br.close();
            }
            if (inputStream != null) {
                inputStream.close();
            }
            if (inputStreamReader != null) {
                inputStreamReader.close();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }

    }
}
